//
//  HttpLogger.m
//  Alarm3DExperiments4
//
//  Created by 우성 김 on 12. 4. 6..
//  Copyright (c) 2012년 yy01ar@gmail.com. All rights reserved.
//

#define DEFAULT_URL @"http://yyar.dothome.co.kr/httplogger/"

#import "HttpLogger.h"

@implementation HttpLogger

@synthesize loggerURL = _loggerURL;

@synthesize rid = _rid;

@synthesize tag = _tag;
@synthesize description = _description;


-(id)initWithURL:(NSString*)url {
    if(self = [super init]) {

        _loggerURL = [NSURL URLWithString: url];
        postData = nil;
        
        [self generateRid];
        queue = [[NSOperationQueue alloc] init];
    }
    return self;
}

-(id)init {
    return [self initWithURL:DEFAULT_URL];
}

-(void)generateRid
{
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: 20];
    
    for (int i=0; i< 20; i++) {
        [randomString appendFormat: @"%c", [letters characterAtIndex: arc4random()%[letters length]]];
    }
    
    _rid = randomString ;
}


-(BOOL)setPostData {
    if(![self canSetPostData]) 
        return NO;
    else {
        postData = [NSString stringWithFormat:@"rid=%@&tag=%@&description=%@", _rid, _tag, _description];
        return YES;
    }
}
       
-(BOOL)canSetPostData {
    return _tag != nil && _description != nil;
}

-(BOOL)hasPostData {
    return postData != nil;
}

// only iOS 5 method
/*
-(void)sendAsyncRequestWithQueue:(NSOperationQueue*)queue andHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handler NS_AVAILABLE(10_7, 5_0); {
    // set Request
    NSString *length = [NSString stringWithFormat:@"%d", [postData length]] ; 
    [request addValue:length forHTTPHeaderField:@"Content-Length"];    
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
    
    // for iOS 5
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:handler];
}
*/

-(void)sendSimpleAsyncRequestWithTag:(NSString *)tag andDescription:(NSString*) description{
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_loggerURL];
    [request setHTTPMethod:@"POST"];
    _tag = tag;
    _description = description;
    
    [self setPostData];
    
    if([self hasPostData]) {
        // set Request
        NSString *length = [NSString stringWithFormat:@"%d", [postData length]] ; 
        [request addValue:length forHTTPHeaderField:@"Content-Length"];    
        [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
        
        // for iOS 5
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * response, NSData *data, NSError *error) {
            // NSLog(@"%@", data); 
            // TODO :: DO NOTHING
        }];
    }
}
@end
